﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
public partial class ViewMessage : System.Web.UI.Page
{
    public int MessageID = 0;
    int result = 0,CommunicationID = 0;
    public string body = string.Empty, Subject = string.Empty, From = string.Empty, To = string.Empty, Cc = string.Empty;
    Communication cs = new Communication();
    RegistrationData reg = new RegistrationData();
    const string svgDataKey = "svgDataKey";
    DataSet ds = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session[svgDataKey] = null;
            //Check whether the proper message is being passed or not
            if (Request.QueryString["MessageID"] != null)
            {
                try
                {
                    MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                    BindMessage(MessageID);
                    Body(MessageID);
                    if (Request.QueryString["type"] != null)
                    {
                        pInbox.Attributes.Add("class", "active");
                        if (Request.QueryString["mBox"] != null)
                        {
                            if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["mBox"])))
                            {
                                if (Session["User"] != null)
                                {
                                    reg = (RegistrationData)Session["User"];
                                    cs.UserID = reg.UserID;
                                    cs.CommunicationID = Convert.ToInt32(Request.QueryString["mBox"]);
                                    cs.MarkAsRead_Message();
                                }
                            }
                        }
                    }
                    else
                        pSent.Attributes.Add("class", "active");
                }
                catch (Exception ex)
                {
                    Response.Redirect(Common.ErrorPage);
                }
            }
            else Response.Redirect("MyAccount.aspx");
        }
    }

    void BindMessage(int ID)
    {
        if (Session["User"] != null)
        {
            ds = new DataSet();
            reg = (RegistrationData)Session["User"];
            cs.UserID = reg.UserID;
            cs.MessageID = ID;
            ds = cs.Select_Messages();
            if (ds != null)
            {
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Sender"])))
                            From = Convert.ToString(dr["Sender"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Subject"])))
                            Subject = Convert.ToString(dr["Subject"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Message"])))
                        {
                            body = Convert.ToString(dr["Message"]);
                        }
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["To"])))
                            To = Convert.ToString(dr["To"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["CC"])))
                            Cc = Convert.ToString(dr["CC"]);
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["SilPath"])))
                        {
                            lnkOpenReviewer.Visible = true;
                            ViewState[svgDataKey] = Convert.ToString(dr["SilPath"]);
                        }
                        else
                        {
                            lnkOpenReviewer.Visible = false;
                        }
                        //if()
                        gvNewFiles.DataSource = ds.Tables[1];
                        gvNewFiles.DataBind();
                    }
                    else AlertMessage();
                }
                else AlertMessage();
            }
            else AlertMessage();
        }
    }

    void Body(int ID)
    {
        System.Text.StringBuilder sbBody = new System.Text.StringBuilder();
        //sbBody.Append("<div style=' border:none;border-left:2px solid #464EEA;'><p style='margin-bottom:5px;'><label style='width:85px; float:left;  text-transform:capitalize; font-weight:bold; font-size:15px;text-align:right;'>From:</label> <label style=' margin-left:5px;'>" + From + " </label></p>" +
        //                    "<p  style='margin-bottom:5px;'><label style='width:85px; float:left;  text-transform:capitalize; font-weight:bold; font-size:15px; text-align:right;'>cc:</label> <label style=' margin-left:5px;'>" + Cc + "</label></p></div>");

        Common.To = To;
        Common.From = From;
        Common.Subject = Subject;
        Common.CC = Cc;
        Common.Body = body;
        if (ViewState[svgDataKey] != null)
        {
            Common.AttachmentPath = "./ALM-Attach_Open.aspx?Silpath=" + Crypto.EncryptStringAES(ID.ToString());
        }
        else
        {
            Common.AttachmentPath = string.Empty;
        }

        Page page = new Page();
        StringWriter sw = new StringWriter();
        UserControl control = (UserControl)page.LoadControl("~/Alumini/UserControls/ALM-RFContent.ascx");
        page.Controls.Add(control);

        HttpContext.Current.Server.Execute(page, sw, false);
        divOldMessage.InnerHtml = sw.ToString();
        // txtbody.Content = sw.ToString();

    }
    void AlertMessage()
    {
        //string script = string.Format("alert('You are not authorized to view this message')");
        //ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", script, true);
        if (Request.QueryString["type"] != null)
            Response.Redirect("ALM-InboxMessageList.aspx");
        else
            Response.Redirect("ALM-SentMessages.aspx");
    }
    protected void gvNewFiles_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "downloadFile":
                string strFolder = "~/Uploads/";
                string filePath = Path.Combine(strFolder, e.CommandArgument.ToString());
                DownloadFile(filePath);
                break;
        }
    }

    public void DownloadFile(string filePath)
    {
        if (File.Exists(Server.MapPath(filePath)))
        {
            string strFileName = Path.GetFileName(filePath).Replace(" ", "%20");
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
            Response.Clear();
            Response.WriteFile(Server.MapPath(filePath));
            Response.End();
        }
    }

    protected void btnPrevious_Click(object sender, EventArgs e)
    {
        if (Session["User"] != null)
        {
            reg = (RegistrationData)Session["User"];
            if (Request.QueryString["MessageID"] != null)
            {
                int ResultMessageID = 0;
                try
                {
                    MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                }
                catch (Exception ex)
                {
                    Response.Redirect(Common.ErrorPage);
                }
                cs.UserID = reg.UserID;
                cs.MessageID = MessageID;
                CommunicationID = 0;

                if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["type"])))
                    ResultMessageID = cs.Select_NextMessage(Convert.ToInt32(Request.QueryString["mbox"]), out CommunicationID,"inbox");
                else
                    ResultMessageID = cs.Select_NextMessage(Convert.ToInt32(Request.QueryString["mbox"]), out CommunicationID, "");
                if (ResultMessageID > 0 && CommunicationID>0)
                {
                    if (Request.QueryString["type"] != null)
                        Response.Redirect("ALM-ViewMessage.aspx?MessageID=" + ResultMessageID.ToString() + "&mBox="+CommunicationID.ToString()+"&type=inbox");
                    else
                        Response.Redirect("ALM-ViewMessage.aspx?MessageID=" + ResultMessageID.ToString() + "&mBox=" + CommunicationID.ToString());

                }
                else
                {

                    if (Request.QueryString["MessageID"] != null)
                    {
                        try
                        {
                            MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                        }
                        catch (Exception ex)
                        {
                            Response.Redirect(Common.ErrorPage);
                        }
                        BindMessage(MessageID);
                    }
                    string script = string.Format("alert('You have reached to first message')");
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", script, true);
                    //Response.Write("<script>" + script + "</script>");
                }

            }
        }
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        if (Session["User"] != null)
        {
            reg = (RegistrationData)Session["User"];
            if (Request.QueryString["MessageID"] != null)
            {
                int ResultMessageID = 0;
                try
                {
                    MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                }
                catch (Exception ex)
                {
                    Response.Redirect(Common.ErrorPage);
                }
                cs.UserID = reg.UserID;
                cs.MessageID = MessageID;
                CommunicationID = 0;
                if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["type"])))
                    ResultMessageID = cs.Select_PreviousMessage(Convert.ToInt32(Request.QueryString["mbox"]),out CommunicationID,"inbox");
                else
                    ResultMessageID = cs.Select_PreviousMessage(Convert.ToInt32(Request.QueryString["mbox"]), out CommunicationID, "");
                if (ResultMessageID > 0 && CommunicationID >0)
                {

                    if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["type"])))
                        Response.Redirect("ALM-ViewMessage.aspx?MessageID=" + ResultMessageID.ToString() + "&mBox=" + CommunicationID+"&type=inbox");
                    else
                        Response.Redirect("ALM-ViewMessage.aspx?MessageID=" + ResultMessageID.ToString() + "&mBox=" + CommunicationID);

                }
                else
                {

                    string script = string.Format("alert('You have reached to last message')");
                    ClientScript.RegisterStartupScript(this.GetType(), "alertScript", script, true);
                    if (Request.QueryString["MessageID"] != null)
                    {
                        try
                        {
                            MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                        }
                        catch (Exception ex)
                        {
                            Response.Redirect(Common.ErrorPage);
                        }
                        BindMessage(MessageID);
                    }
                    Response.Write("<script>" + script + "</script>");
                }

            }
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (Session["User"] != null)
        {
            if (Request.QueryString["MessageID"] != null)
            {
                reg = (RegistrationData)Session["User"];
                cs.UserID = reg.UserID;
                if (Request.QueryString["type"] != null)
                {
                    try
                    {
                        cs.CommunicationID = Convert.ToInt32(Request.QueryString["mBox"]);
                        result = cs.Delete_InboxMessage();
                        if (result > 0)
                        {
                            Response.Redirect("ALM-InboxMessageList.aspx");
                        }
                    }
                    catch (Exception ex)
                    {
                       // Response.Redirect(Common.ErrorPage);
                    }
                }
                else
                {
                    try
                    {
                        MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
                        cs.MessageID = MessageID;
                        result = cs.Delete_SentMessage();
                        if (result > 0)
                        {
                            Response.Redirect("ALM-SentMessages.aspx");
                        }
                    }
                    catch (Exception ex)
                    {
                       // Response.Redirect(Common.ErrorPage);
                    }
                }
            }
        }
    }
    protected void btnReply_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["type"] != null && Request.QueryString["mBox"] != null)
        {
            Response.Redirect("ALM-RFCompose.aspx?MessageID=" + Convert.ToString(Request.QueryString["MessageID"]) + "&mBox=" + Convert.ToString(Request.QueryString["mBox"]) + "&Action=Reply");
        }
        else
            Response.Redirect("ALM-RFCompose.aspx?MessageID=" + Convert.ToString(Request.QueryString["MessageID"]) + "&Action=Reply");
    }
    protected void btnForward_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["mBox"] != null)
        {
            Response.Redirect("ALM-RFCompose.aspx?MessageID=" + Convert.ToString(Request.QueryString["MessageID"]) + "&mBox=" + Convert.ToString(Request.QueryString["mBox"]) + "&Action=Forward");
        }
        else
            Response.Redirect("ALM-RFCompose.aspx?MessageID=" + Convert.ToString(Request.QueryString["MessageID"]) + "&Action=Forward");
    }

    protected void lnkOpenReviewer_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState[svgDataKey])))
        {
            Session[svgDataKey] = ViewState[svgDataKey].ToString();
            string url = ViewState[svgDataKey].ToString();
            string script = "window.open('" + url + "','')";
            if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", script, true);
            }
        }
        if (Request.QueryString["MessageID"] != null)
        {
            try
            {
                MessageID = Convert.ToInt32(Request.QueryString["MessageID"]);
            }
            catch (Exception ex)
            {
                Response.Redirect(Common.ErrorPage);
            }
            BindMessage(MessageID);
        }

    }
}